package com.zhimu.activemq_demo.activemq.queue;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * @Author: Alvin
 * @Date: 2019/6/22 09:37
 * @Description
 */
public class JmsConsumer_TX {

    public static final String ACTIVE_URL = "tcp://127.0.0.1:61616";

    public static final String QUEUE_NAME = "queue_tx01";

    public static void main(String[] args) throws JMSException, IOException {

        // 1、创建连接工厂,按照给定URL，默认账号密码
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ACTIVE_URL);
        // 2、通过连接工厂，获得connection，并启动访问
        Connection connection = connectionFactory.createConnection();
        connection.start();
        // 3、创建会话Session
        // 两个参数，第一个叫事务，第二个叫签收
        Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
        // 4、创建目的地（具体是队列还是主题）
        Queue queue = session.createQueue(QUEUE_NAME);
        // 5、创建消费者
        MessageConsumer messageConsumer = session.createConsumer(queue);
        // 6、接收消息

        while (true) {
            Message message = messageConsumer.receive(4000L);
            if (null != message) {
                TextMessage textMessage = (TextMessage) message;
                System.out.println("tx 消费者接收到的消息：" + textMessage.getText());
                textMessage.acknowledge();
            }else {
                break;
            }
        }
        // 7、关闭资源
        messageConsumer.close();
        session.commit();
        session.close();
        connection.close();
        System.out.println("*******************tx消费者接收信息完成");


    }
}
